import fs from 'fs'; import path from 'path';

const DIRECTORY_NAME = path.resolve();
const PLUGIN_PATH = path.join(DIRECTORY_NAME, 'plugins', 'Farming-Simulator');
const FILE_PATH = {
    player: path.join(PLUGIN_PATH, 'data', 'player'),
    vegetable: path.join(PLUGIN_PATH, 'data', 'Vegetable.json'),
    StealingVegetables: path.join(PLUGIN_PATH, 'data', 'StealingVegetables.json')
};

/** 读取玩家数据 */
export async function getPlayerData(ID) {
    const DATA = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['player'], ID + '.json'), 'utf8'))
    return DATA
}

/** 读取蔬菜数据 */
export async function getVegetableData() {
    const DATA = await JSON.parse(fs.readFileSync(FILE_PATH['vegetable']), 'utf8')
    return DATA
}

/** 读取偷菜数据 */
export async function getStolenVegetableData() {
    const data = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['StealingVegetables']), 'utf8'))
    return data
}

/** 存储玩家数据 */
export function storagePlayerData(ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], ID + '.json'), JSON.stringify(DATA, null, 4));
}

/** 存储偷菜数据 */
export function storeStolenVegetableData(DATA) {
    fs.writeFileSync(path.join(FILE_PATH['StealingVegetables']), JSON.stringify(DATA, null, 4));
}

/** 休眠 */
export function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

/** 判断玩家是否存在 */
export function isPlayerExist(ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], ID + '.json'))) {
        return true
    }
    return false
}

/** 读取文件夹返回文件列表 */
export function getPlayerList() {
    return fs.readdirSync(FILE_PATH['player'])
}

/** 将时间戳转换为DD:HH:MM:SS */
export function timeConversion(TIMESTAMP) {
    const DIFFERENCE_VALUE = Date.now() - TIMESTAMP;
    const DD = String(Math.floor(DIFFERENCE_VALUE / (1000 * 60 * 60 * 24))).padStart(2, '0');
    const HH = String(Math.floor((DIFFERENCE_VALUE % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, '0');
    const MM = String(Math.floor((DIFFERENCE_VALUE % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0');
    const SS = String(Math.floor((DIFFERENCE_VALUE % (1000 * 60)) / 1000)).padStart(2, '0');
    return { DD, HH, MM, SS };
}

/** 将时间戳转换为秒 */
export function timestampToSeconds(TIMESTAMP) {
    return Math.floor(TIMESTAMP / 1000);
}
